<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" size="medium" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" size="medium" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>

      <div class="block">
        <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id">
          <el-table-column
            prop="id"
            label="ID"
            width="80">
          </el-table-column>
          <el-table-column
            prop="display_name"
            label="角色名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述">
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="创建日期"
            width="180">
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

              <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' icon="el-icon-info" icon-color="red" title="确定删除吗？" @onConfirm="() => handleDelete(scope.$index, scope.row)">
                <el-button slot="reference" size="mini" type="danger">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名" prop="display_name">
          <el-input v-model="temp.display_name" placeholder="输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="name">
          <el-input v-model="temp.name" placeholder="输入角色标识" />
        </el-form-item>
        <el-form-item label="权限" prop="permission">
          <el-tree
            :data="permissionData"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="菜单描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="temp.status" active-value="1" inactive-value="2" active-text="正常" inactive-text="冻结"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import waves from '@/directive/waves'
import { addRole, getRoutes, updateRole, deleteRole } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import Pagination from '@/components/Pagination'
export default {
  name: 'Roles',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        type: undefined
      },
      tableData: [],
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      rules: {
        display_name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '请输入唯一标识', trigger: 'blur' }]
      },
      temp: {
        id: undefined,
        name: '',
        display_name: '',
        description: '',
        permission: [],
        status: '1'
      },
      permissionData: [],
      defaultProps: {
        children: 'children',
        label: 'display_name'
      }
    }
  },
  created() {
    this.getList()
    this.getPermissionList()
  },
  methods: {
    getList() {
      getRoutes(this.listQuery).then(response => {
        if (response.code === 200) {
          this.tableData = response.data.rows
          this.total = response.data.total
        }
        this.resetTemp()
      })
    },
    getPermissionList() {
      getPermissionList().then(response => {
        if (response.code === 200) {
          this.permissionData = response.data.row
        }
      })
    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.cascader_val = []
      this.temp = {
        id: undefined,
        name: '',
        display_name: '',
        description: '',
        permission: [],
        status: '1'
      }
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([])
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      var permission = []
      for (const indexd in row.permissionIds) {
        permission.push(row.permissionIds[indexd])
      }
      this.temp = {
        id: row.id,
        name: row.name,
        display_name: row.display_name,
        description: row.description,
        permission: permission,
        status: row.status.toString()
      }
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(permission)
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(index, row) {
      deleteRole(row.id).then(response => {
        if (response.code === 200) {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getList()
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.permission = this.$refs.tree.getCheckedKeys()
          console.log(this.temp)
          addRole(this.temp).then(response => {
            if (response.code === 200) {
              this.$message({
                message: response.msg,
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.permission = this.$refs.tree.getCheckedKeys()
          console.log(this.temp)
          updateRole(this.temp).then(response => {
            if (response.code === 200) {
              this.$message({
                message: response.msg,
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    closeDialog() {
      this.resetTemp()
    }
  }
}
</script>

<style scoped>

</style>
